const { homeworkApi } = require('../../../utils/api');
const auth = require('../../../utils/auth');
const tips = require('../../../utils/tips');

Page({
  data: {
    userInfo: null,
    currentDate: '',
    // 统计数据
    stats: {
      totalHomework: 0,
      pendingReview: 0,
      completedToday: 0,
      averageScore: 0
    },
    // 快速操作
    quickActions: [
      {
        name: '布置作业',
        emoji: '📝',
        color: '#667eea',
        path: '/pages/class/homework/create/index',
        desc: '创建新的作业'
      },
      {
        name: '批改作业',
        emoji: '✏️',
        color: '#43e97b',
        path: '/pages/class/homework/review/index',
        desc: '批改学生作业'
      },
      {
        name: '作业统计',
        emoji: '📊',
        color: '#f093fb',
        path: '/pages/class/homework/statistics/index',
        desc: '查看作业数据'
      },
      {
        name: '草稿箱',
        emoji: '📁',
        color: '#4facfe',
        path: '/pages/class/homework/draft/index',
        desc: '管理草稿作业'
      }
    ],
    // 最近作业
    recentHomework: [],
    // 页面状态
    loading: false,
    refresherTriggered: false
  },

  onLoad(options) {
    console.log('作业页面加载');
    this.initCurrentDate();
    this.checkLoginStatus();
    this.loadHomeworkData();
  },

  onShow() {
    this.loadHomeworkData();
  },

  // 初始化当前日期
  initCurrentDate() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    const weekday = weekdays[now.getDay()];
    
    this.setData({
      currentDate: `${year}年${month}月${day}日 ${weekday}`
    });
  },

  // 检查登录状态
  checkLoginStatus() {
    if (!auth.isLoggedIn()) {
      console.log('用户未登录，跳转到登录页');
      auth.goToLogin();
      return;
    }
    
    const userInfo = auth.getUserInfo();
    this.setData({
      userInfo: userInfo
    });
    console.log('用户已登录:', userInfo);
  },

  // 加载作业数据
  async loadHomeworkData() {
    try {
      this.setData({ loading: true });
      
      // 加载统计数据
      await this.loadStats();
      
      // 加载最近作业
      await this.loadRecentHomework();
      
    } catch (error) {
      console.error('加载作业数据失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    } finally {
      this.setData({ loading: false });
    }
  },

  // 加载统计数据
  async loadStats() {
    try {
      // 模拟统计数据
      const stats = {
        totalHomework: Math.floor(Math.random() * 50) + 20,
        pendingReview: Math.floor(Math.random() * 15) + 5,
        completedToday: Math.floor(Math.random() * 25) + 10,
        averageScore: Math.floor(Math.random() * 20) + 80
      };
      
      this.setData({ stats });
    } catch (error) {
      console.error('加载统计数据失败:', error);
    }
  },

  // 加载最近作业
  async loadRecentHomework() {
    try {
      // 模拟最近作业数据
      const recentHomework = [
        {
          id: 1,
          title: '数学练习册第3章',
          subject: '数学',
          class: '六年级一班',
          status: 'reviewing',
          submitCount: 28,
          totalCount: 32,
          deadline: '2024-01-20',
          createTime: '2024-01-15'
        },
        {
          id: 2,
          title: '英语单词背诵',
          subject: '英语',
          class: '六年级二班',
          status: 'completed',
          submitCount: 30,
          totalCount: 30,
          deadline: '2024-01-18',
          createTime: '2024-01-10'
        },
        {
          id: 3,
          title: '语文作文练习',
          subject: '语文',
          class: '六年级三班',
          status: 'draft',
          submitCount: 0,
          totalCount: 25,
          deadline: '2024-01-25',
          createTime: '2024-01-19'
        }
      ];
      
      this.setData({ recentHomework });
    } catch (error) {
      console.error('加载最近作业失败:', error);
    }
  },

  // 下拉刷新
  async onRefresh() {
    console.log('下拉刷新');
    this.setData({
      refresherTriggered: true
    });
    
    try {
      await this.loadHomeworkData();
      wx.showToast({
        title: '刷新成功',
        icon: 'success',
        duration: 1000
      });
    } catch (error) {
      wx.showToast({
        title: '刷新失败',
        icon: 'none'
      });
    } finally {
      this.setData({
        refresherTriggered: false
      });
    }
  },

  // 快速操作点击
  onQuickActionTap(e) {
    const path = e.currentTarget.dataset.path;
    const name = e.currentTarget.dataset.name;
    
    if (path) {
      // 检查是否为开发中的功能
      if (path.includes('statistics') || path.includes('draft')) {
        wx.showToast({
          title: `${name}功能开发中`,
          icon: 'none'
        });
      } else {
        wx.navigateTo({ url: path });
      }
    }
  },

  // 查看作业详情
  onHomeworkDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/class/homework/detail/index?id=${id}`
    });
  },

  // 创建新作业
  onCreateHomework() {
    wx.navigateTo({
      url: '/pages/class/homework/create/index'
    });
  },

  // 查看全部作业
  onViewAllHomework() {
    wx.navigateTo({
      url: '/pages/class/homework-list/index'
    });
  },

  // 批改作业
  onReviewHomework(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/class/homework/review/index?id=${id}`
    });
  },

  // 编辑作业
  onEditHomework(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/class/homework/edit/index?id=${id}`
    });
  },

  // 删除作业
  onDeleteHomework(e) {
    const id = e.currentTarget.dataset.id;
    const title = e.currentTarget.dataset.title;
    
    wx.showModal({
      title: '确认删除',
      content: `确定要删除"${title}"吗？删除后无法恢复。`,
      success: (res) => {
        if (res.confirm) {
          this.deleteHomework(id);
        }
      }
    });
  },

  // 删除作业
  async deleteHomework(id) {
    try {
      wx.showLoading({ title: '删除中...' });
      
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 1000));
      
      // 从列表中移除
      const recentHomework = this.data.recentHomework.filter(item => item.id !== id);
      this.setData({ recentHomework });
      
      wx.hideLoading();
      wx.showToast({
        title: '删除成功',
        icon: 'success'
      });
      
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  }
});